package org.platform.lwc.gateway.filter;

import cn.hutool.core.util.StrUtil;
import org.platform.lwc.gateway.config.IgnoreConfig;
import org.platform.lwc.tool.auth.constants.AuthConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

/**
 * url白名单路径访问时需要移除JWT请求头
 *
 * 明明就是个url白名单接口，只不过携带的token(过期或者没过期的，会报没权限)不对就不让访问了，显然有点不合理。如何解决呢？
 * 直接移除认证头即可
 */
@Component
public class IgnoreUrlsRemoveJwtFilter implements WebFilter {
    @Autowired
    private IgnoreConfig ignoreConfig;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {

        if (StrUtil.startWith( exchange.getRequest().getHeaders().getFirst(AuthConstant.BASIC_HEADER_KEY),AuthConstant.BASIC_HEADER_BASIC)){
            //请求头值里面带basic 的不移除 ,需要传到认证服务器进行授权登陆
            return chain.filter(exchange);
        }
        ServerHttpRequest request = exchange.getRequest();
        URI uri = request.getURI();
        PathMatcher pathMatcher = new AntPathMatcher();
        //白名单路径移除JWT请求头
        List<String> ignoreUrls = ignoreConfig.getUrls();
        for (String ignoreUrl : ignoreUrls) {
            if (pathMatcher.match(ignoreUrl, uri.getPath())) {
                request = exchange.getRequest().mutate().header(AuthConstant.BASIC_HEADER_KEY, "").build();
                exchange = exchange.mutate().request(request).build();
                return chain.filter(exchange);
            }
        }
        return chain.filter(exchange);
    }
}
